<script>
// @ is an alias to /src
import { marked } from "./marked";
import { debounce } from "./lodash-es";
import TreeItem from "./TreeItem.vue";
import JSConfetti from "js-confetti";
import { prevSnippetField } from "@codemirror/autocomplete";


const confetti = new JSConfetti();

//----------------------------------------------------------------markdown
const IndexData = {
    name: "目录",
    children: [{
        name: "大纲", markdowntext: "",
        outtext: "", children: []
    }],
    markdowntext: "",
    outtext: "",
    parent: null
};

let PresetEntryModifyReasonsid = 0;

export default {
    components: {
        TreeItem
    },
    data() {
        return {
            user: '',
            entity: "",
            url: '',
            input: "#### 输入词条的主要内容介绍，例如\n\r克里斯蒂亚诺·罗纳尔多·多斯·桑托斯·阿维罗（Cristiano Ronaldo dos Santos Aveiro），简称“C罗”，1985年2月5日出生于葡萄牙马德拉岛丰沙尔，葡萄牙职业足球运动员，司职边锋、中锋，效力于意大利尤文图斯足球俱乐部，并身兼葡萄牙国家男子足球队队长。\n\rC罗出道于里斯本竞技。2003年加盟英超曼联，期间获得了英格兰足球超级联赛冠军、欧洲冠军联赛冠军、世俱杯冠军等十个赛事冠军。\n2009年6月以身价9600万欧元转会至西甲皇马，期间获得了4次欧洲冠军联赛冠军、2次西甲联赛冠军、3次世俱杯冠军等十六个赛事冠军。C罗效力皇马9年时间，438场比赛贡献450球、131次助攻，以场均1.03球的进球率成为皇马历史上进球率最高的球员。\n C罗职业生涯保持着多项个人记录，包括欧洲五大联赛个人总进球记录、皇马俱乐部个人总进球记录、欧冠联赛个人总进球记录、欧洲国家队个人总进球记录等。C罗已5次获得金球奖、3次获得世界足球先生、4次获得欧洲金靴奖、7次获得欧冠最佳射手等个人荣誉。",
            output: "",
            ShowPreview: false,
            EntryNamemarkdowntext:
                "#### 所有词条的名称都应浅显易懂，使用最容易理解、最不容易混淆的文字，例如\n\r克里斯蒂亚诺·罗纳尔多·多斯·桑托斯·阿维罗（Cristiano Ronaldo dos Santos Aveiro），简称“C罗”，葡萄牙职业足球运动员",
            EntryNameouttext: "例如：克里斯蒂亚诺·罗纳尔多",
            EntryChineseName: "例如：克里斯蒂亚诺·罗纳尔多·多斯·桑托斯·阿维罗",
            EntryForeignName: "例如：Cristiano Ronaldo dos Santos Aveiro",
            EntryBriefName: "例如：c罗",
            EntryOtherName: "例如：小小罗、CR7",
            EntryKind: "例如：足球",
            IndexData,
            IndexContent: "",
            ReferContent: "",
            Content: "",
            precontent: '',
            zwm: ' \n\r **中文名：**',
            ywm: " \n\r **英文名：**",
            jm: " \n\r **简名：**",
            qtm: " \n\r **其他名：**",
            ctl: " \n\r **词条类：**",
            ctml: " <br><br>\n\r #### 词条目录 \n\r *** \n\r ``` \n\r ",
            ctzw: " \n\r ``` \n\r<br><br>\n\r #### 词条正文 \n\r *** \n\r ",
            ckzl: " <br><br>\n\r #### 参考资料 \n\r *** \n\r ",
            infotxt: '',
            indexs:[],
            indextxt:'',
            refers:[],
            refertxt:'',
            //------------------------------
            PresetEntryModifyReasons: [
                { id: PresetEntryModifyReasonsid++, text: "改正错误", selected: false },
                { id: PresetEntryModifyReasonsid++, text: "内容扩充", selected: false },
                { id: PresetEntryModifyReasonsid++, text: "删除冗余", selected: false },
                { id: PresetEntryModifyReasonsid++, text: "修改概述", selected: false },
                { id: PresetEntryModifyReasonsid++, text: "调整排版", selected: false },
                { id: PresetEntryModifyReasonsid++, text: "参考资料", selected: false },
            ],
            EntryModifyReasons: [],
            OtherEntryModifyReasons: "",
            //-------------------------------
        };
    },
    computed: {
        output() {
            if (this.input != "")
                return marked(this.input);
        },
        EntryNameouttext() {
            if (this.EntryNamemarkdowntext != "")
                return marked(this.EntryNamemarkdowntext);
        },

    },
    methods: {

        Infoouttext() {
            this.infotxt = ""
            this.infotxt += this.zwm;
            this.infotxt += this.EntryChineseName != "" ? (this.EntryChineseName) : "无";
            this.infotxt += " \n\r "+this.ywm;
            this.infotxt += this.EntryForeignName != "" ? (this.EntryForeignName) : "无";
            this.infotxt += " \n\r "+this.jm;
            this.infotxt += this.EntryBriefName != "" ? (this.EntryBriefName) : "无";
            this.infotxt +=  " \n\r "+this.qtm;
            this.infotxt += this.EntryOtherName != "" ? (this.EntryOtherName) : "无";
            this.infotxt +=  " \n\r "+this.ctl;
            this.infotxt += this.EntryKind != "" ? (this.EntryKind) : "无";
            var tmp=this.infotxt
            this.infotxt= marked(this.infotxt)
            return tmp
        },
        IndexoutText(){
            this.indextxt=''
            console.log(this.indexs)
            var fl=false
            this.indexs.forEach(a => {
                if(!fl)fl=true
                else this.indextxt+='\n\r'
                if(a!="")
                this.indextxt+=a
            });
            var tmp=this.indextxt
            this.indextxt=marked(this.indextxt)
            return tmp
        },
        ReferoutText(){
            this.refertxt=''
            console.log(this.refers)
            var fl=false
            this.refers.forEach(a => {
                if(!fl)fl=true
                else this.refertxt+='\n\r'
                if(a!="")
                this.refertxt+=a
            });
            var tmp=this.refertxt
            this.refertxt=marked(this.refertxt)
            return tmp
        },
        alrt(s) {
            alert(s)
        },
        //更新markdown
        update(e) {
            this.input = e.target.value;
            if (this.input != "")
                this.output = marked(this.input);
        },
        updateEntryName: debounce(function (e) {
            this.EntryNamemarkdowntext = e.target.value;
            if (this.EntryNamemarkdowntext != "")
                this.EntryNameouttext = marked(this.EntryNamemarkdowntext);
        }, 100),
        //装逼
        showConfetti() {
            confetti.addConfetti();
        },

        showDetails(num) {
            var el = document.getElementById("123")[0];
            if (this.showIndex == num) {
                this.showIndex = null;
            } else {
                this.showIndex = num;
            }
            this.$nextTick(function () {
                window.scrollTo({ behavior: "smooth", top: el.offsetTop });
            });
        },

        ReasonButtonClicked(reason) {
            this.PresetEntryModifyReasons[reason.id].selected =
                !this.PresetEntryModifyReasons[reason.id].selected;
            if (this.PresetEntryModifyReasons[reason.id].selected)
                this.EntryModifyReasons.push(reason.text);
            else {
                for (let i = 0; i < this.EntryModifyReasons.length; i++) {
                    if (this.EntryModifyReasons[i] == reason.text) {
                        this.EntryModifyReasons.splice(i, 1)
                    }
                }
            }
        },
        submitEntry() {
            if (this.user) {
                this.Content=""
                this.Content += this.EntryNamemarkdowntext;
                this.Content += this.zwm;
                this.Content += this.EntryChineseName != "" ? (this.EntryChineseName) : "无";
                this.Content += this.ywm;
                this.Content += this.EntryForeignName != "" ? (this.EntryForeignName) : "无";
                this.Content += this.jm;
                this.Content += this.EntryBriefName != "" ? (this.EntryBriefName) : "无";
                this.Content += this.qtm;
                this.Content += this.EntryOtherName != "" ? (this.EntryOtherName) : "无";
                this.Content += this.ctl;
                this.Content += this.EntryKind != "" ? (this.EntryKind) : "无";
                this.IndexContent=this.IndexoutText()
                this.Content += this.ctml + this.IndexContent;
                this.Content += this.ctzw + this.input
                this.ReferContent=this.ReferoutText()
                this.Content += this.ckzl + this.ReferContent;


                console.log(this.Content)
                this.$confirm('是否发送添加请求?', '提示', {

                })
                    .then(() => {
                        this.axios.post('/entity/update_entity', {
                            "url": this.url,
                            "content": this.Content
                        }).then(res => {
                            console.log(res)
                            if (res.code === '0') {
                                this.showConfetti()
                                this.$message({
                                    type: 'success',
                                    message: '请求发送成功'
                                })
                            }
                            else {
                                this.$message({
                                    type: 'warning',
                                    message: '请求发送失败，请重试'
                                })
                            }
                        })
                    })
                    .catch(() => {
                        this.$message({
                        })
                    })
            }
            else {
                this.$router.push('/login')
            }

        },
    },
    directives: {
        // 在模板中启用 v-focus
    },
    created() {
        this.user = sessionStorage.getItem("user")


        let self = this;
        self.precontent = "123"
        self.searchContent = "pop"

        self.url = this.$route.query.url;
        self.precontent = this.$route.query.content;
        self.searchContent = this.$route.query.searchContent;
        console.log(self.url)
        console.log(self.searchContent)


        //初始化字符
        this.EntryNamemarkdowntext = self.searchContent
        var zwm = this.precontent.indexOf(this.zwm)
        var ywm = this.precontent.indexOf(this.ywm)
        var jm = this.precontent.indexOf(this.jm)
        var qtm = this.precontent.indexOf(this.qtm)
        var ctl = this.precontent.indexOf(this.ctl)
        var ctml = this.precontent.indexOf(this.ctml)
        var ctzw = this.precontent.indexOf(this.ctzw)
        var ckzl = this.precontent.indexOf(this.ckzl)

        if (zwm == -1)
            this.EntryChineseName = ""
        else{
            this.EntryChineseName = self.precontent.slice(zwm, ywm).slice(this.zwm.length)
            this.EntryNamemarkdowntext = self.precontent.slice(0, zwm)
        }

        if (ywm == -1)
            this.EntryForeignName = ""
        else
            this.EntryForeignName = self.precontent.slice(ywm, jm).slice(this.ywm.length)

        if (jm == -1)
            this.EntryBriefName = ""
        else
            this.EntryBriefName = self.precontent.slice(jm, qtm).slice(this.jm.length)

        if (qtm == -1)
            this.EntryOtherName = ""
        else
            this.EntryOtherName = self.precontent.slice(qtm, ctl).slice(this.qtm.length)

        if (ctl == -1)
            this.EntryKind = ""
        else
            this.EntryKind = self.precontent.slice(ctl, ctml).slice(this.ctl.length)


        if (ctml == -1 || ctzw == -1 || ckzl == -1) {

            this.IndexContent = ""
            this.input = this.precontent
            this.ReferContent = ""
            console.log("format error")
        }
        else {

            this.IndexContent = self.precontent.slice(ctml, ctzw).slice(this.ctml.length)
            this.indexs=this.IndexContent.split("\n\r")
            this.input = self.precontent.slice(ctzw, ckzl).slice(this.ctzw.length)
            this.ReferContent = self.precontent.slice(ckzl).slice(this.ckzl.length)
            this.refers=this.ReferContent.split("\n\r")
            console.log("right format")
        }

    }

};

</script>
<template>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Edit blog</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />

    <body class="bg-light" style="padding: 0px;">
        <div>
            <nav class=" navbar navbar-expand-md navbar-dark bd-navbar container-xxl m-0" style="display:flex;">

                <!--<img class="blog-header-logo" src="../assets/bootstrap-solid.svg" alt="" width="44" height="44">-->
                <a class="blog-header-logo col-8 p-2" style=" font-family:思源黑体;" href="#">词条编辑</a>
                <div class=" row p-1">
                    <button v-bind:class="{
                        'btn-primary': ShowPreview,
                        'btn-outline-primary': !ShowPreview,
                    }" class="btn ml-2 btn-lg" @click="ShowPreview = !ShowPreview;Infoouttext();ReferoutText();IndexoutText()">
                        预览
                    </button>
                    <button class="btn btn-lg ml-2 btn-primary " @click="alrt('保存成功!')">保存</button>
                    <button type="button" class="btn btn-lg ml-2 btn-primary" data-bs-toggle="modal"
                        data-bs-target="#myModal" href="#">
                        提交
                    </button>
                </div>
            </nav>
            <div class="container-xxl my-md-4 bd-layout ">
                <aside class="bd-sidebar card bg-white bg-gradient" id="sticky-sidebar" style="border-radius:9px">
                    <div class="sticky-top m-2 p-2 " style="border-radius:9px;height: 100%;">
                        <div class="p-4 m-2 bg-light" style="border-radius:9px">
                            <h4 class="m-2">词条图片</h4>
                            <img id="image-preview" />
                            <input class="btn btn-sm btn-file" type="file" name="upload_image" style="cursor: pointer;"
                                accept="image/jpg" />
                        </div>

                        <div class="p-4 m-2 bg-light" style="border-radius:9px">
                            <div class="row m-2" ><h4 class=" m-2 ">目录</h4><button class="btn btn-xs m-2 btn-outline-secondary" style="border-radius:5px" placeholder="增加" @click="indexs.push('')">增加</button><button class="btn btn-xs m-2 btn-outline-secondary" style="border-radius:5px" placeholder="减少" @click="indexs.pop()">减少</button></div>
                            <div v-for="(a,i) in indexs" :key="i">
                            <input class="form-control m-1 bg-light" v-model="indexs[i]" placeholder="键入想输入的目录" />
                            </div>

                        </div>

                        <div class="p-4 m-2 bg-light" style="border-radius:9px">
                            <div class="row m-2"><h4 class="m-2 ">参考资料</h4><button class="btn btn-xs m-2 btn-outline-secondary" style="border-radius:5px" placeholder="增加" @click="refers.push('')">增加</button><button class="btn btn-xs m-2 btn-outline-secondary" style="border-radius:5px" placeholder="减少" @click="refers.pop()">减少</button></div>
                            <div  v-for="(a,i) in refers" :key="i">
                            <input class="form-control m-1 bg-light" v-model="refers[i]" placeholder="键入想输入的参考资料"/>
                            </div>
                            

                        </div>
                    </div>

                </aside>
                <main class="bd-main order-1">
                    <!-- /.blog-sidebar -->
                    <div class="" style="">
                        <div class="mb-2 bg-white card" style="border-radius:9px">
                            <h4 class="p-4 m-2 bg-light" style=" font-family:思源黑体;border-radius:9px">词条名</h4>
                            <div id="EditMark" class=" p-2 ">
                                <div v-if="!ShowPreview">
                                    <textarea class="input" style="width:100%" v-model="EntryNamemarkdowntext"
                                        @input="updateEntryName"></textarea>
                                </div>
                                <div v-else>
                                    <div class="output" v-html="EntryNameouttext"></div>
                                </div>
                            </div>
                        </div>
                        <div class="mb-2 mt-2 bg-white card" style="border-radius:9px">
                            <h4 class="p-4 m-2 bg-light" style="font-family: 思源黑体;border-radius:9px">信息栏</h4>
                            <p class="blog-post-meta ml-3" v-if="!ShowPreview">
                                注：未填写内容的正文目录将不会显示在词条页上
                            </p>
                            <form class="p-2 m-2" v-if="!ShowPreview">
                                <div class="row m-1">
                                    <div class="col">
                                        <input type="text" class="form-control" v-model="EntryChineseName"
                                            placeholder="中文名" />
                                    </div>
                                    <div class="col">
                                        <input type="text" class="form-control" v-model="EntryForeignName"
                                            placeholder="外文名" />
                                    </div>
                                    <div class="col">
                                        <input type="text" class="form-control" v-model="EntryBriefName"
                                            placeholder="简称"  />
                                    </div>
                                </div>
                                <div class="row m-1">
                                    <div class="col">
                                        <input type="text" class="form-control" v-model="EntryOtherName"
                                            placeholder="别名" />
                                    </div>
                                    <div class="col">
                                        <input type="text" class="form-control" v-model="EntryKind" placeholder="类别"
                                             />
                                    </div>
                                </div>
                            </form>
                            <div v-else>
                                <div class="output" v-html="infotxt"></div>
                            </div>
                        </div>
                        <div class="mb-2 mt-2 bg-white card" style="border-radius:9px" v-if="ShowPreview">
                            <h4 class="p-4 m-2 bg-light" style="font-family: 思源黑体;border-radius:9px">目录</h4>
                            <div>
                                <div class="output" v-html="indextxt"></div>
                            </div>
                        </div>



                        <div class=" bg-white pb-2 mb-2 card height-content" style="border-radius:9px">
                            <h4 class="p-4 m-2 bg-light" style="font-family: 思源黑体;border-radius:9px">正文</h4>
                            <p class="blog-post-meta ml-3" v-if="!ShowPreview">
                                注：未填写内容的正文目录将不会显示在词条页上
                            </p>

                            <div id="EditMark " class="p-2 ">
                                <div v-if="!ShowPreview">
                                    <textarea class="input"  style="width:100%" :value="input" @input="update"></textarea>
                                </div>
                                <div v-else>
                                    <div class="output" v-html="output"></div>
                                </div>
                            </div>
                        </div>
                        <div class="mb-2 mt-2 bg-white card " style="border-radius:9px" v-if="ShowPreview">
                            <h4 class="p-4 m-2 bg-light" style="font-family: 思源黑体;border-radius:9px">参考资料</h4>
                            <div>
                                <div class="output" v-html="refertxt"></div>
                            </div>
                        </div>
                    </div>
                    <!-- /.blog-main -->


                </main>
            </div>
            <!-- /.row -->
        </div>
        <!-- /.container -->
        <div class="modal fade" id="myModal">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <!-- 模态框头部 -->
                    <div class="modal-header">
                        <h5 class="modal-title">词条修改原因</h5>
                    </div>
                    <div class="row ml-2 pt-2">
                        <tr v-for="reason of PresetEntryModifyReasons" :key="reason.id" v-if="true">
                            <th>
                                <button v-bind:class="{
                                    'btn-light': !reason.selected,
                                    'btn-secondary': reason.selected,
                                }" class="btn m-2 p-1" @click="ReasonButtonClicked(reason)">
                                    {{ reason.text }}
                                </button>
                            </th>
                        </tr>
                        <!--{{ EntryModifyReasons }}-->
                    </div>
                    <!-- 模态框内容 -->
                    <div class="modal-body">
                        <div class="form-group">
                            <label for="exampleFormControlTextarea1"
                                class="alert alert-light">小程序百科只收录真实、客观、中立的内容，请确保您提交的内容真实有效，您将对您提供的内容负法律责任。</label>
                            <textarea class="form-control" id="exampleFormControlTextarea1" placeholder="输入其他原因..."
                                v-model="OtherEntryModifyReasons" rows="3"></textarea>
                        </div>
                        <!--{{
                "选项：" +
                EntryModifyReasons +
                " 其他原因：" +
                OtherEntryModifyReasons
        }}-->
                    </div>

                    <!-- 模态框底部 -->
                    <div class="modal-footer">
                        <button type="button" class="btn" data-bs-dismiss="modal">
                            取消
                        </button>
                        <button type="button" class="btn btn-primary" data-bs-dismiss="modal" @click="submitEntry">
                            提交
                        </button>
                    </div>
                </div>
            </div>
        </div>
        <footer class="bd-footer p-3 p-md-5 mt-5 bg-light text-center text-sm-start">
            <p>EntryEdit<br /><a>Copyright</a> © <a>2022-2023 ZJU_TEAM</a>.</p>
            <p>
                <a href="javascript:scroll(0,0)" id="top">回</a>
            </p>
        </footer>
    </body>
</template>

<style scoped>
@import "EntryEdit.css";

body {
    margin: 0;
}

.item {
    width: 100%;
    height: 30px;
    background-color: #f3f3f3;
    border: 1px solid #666;
    box-sizing: border-box;
}

.bold {
    font-weight: bold;
}

/* 1. 声明过渡效果 */
.fade-move,
.fade-enter-active,
.fade-leave-active {
    transition: all 0.5s cubic-bezier(0.55, 0, 0.1, 1);
}

/* 2. 声明进入和离开的状态 */
.fade-enter-from,
.fade-leave-to {
    opacity: 0;
    transform: scaleY(0.01) translate(30px, 0);
}

/* 3. 确保离开的项目被移除出了布局流
          以便正确地计算移动时的动画效果。 */
.fade-leave-active {
    position: absolute;
}

.height-title {
    height: 10vh;
}

.height-intro {
    height: 20vh;
}

.height-content {
    padding-bottom: 2px;
    overflow-y: hidden;
    min-height: 80vh;
}

.bd-footer {
    font-size: .875rem;
    color: #63707c;
}

.bd-main {
    display: grid;
    gap: inherit;
    grid-template-areas:
        "intro"
        "toc"
        "content";
    grid-template-rows: auto auto 1fr;
}

.input,
.output {
    min-height: 100px;
    font-size: medium;
    height: 100%;
    width: 100%;
    border: none;
    border-right: 1px;
    resize:vertical;
    padding: 22px;
}

/*.input {
      border: none;
      border-right: 1px solid #ccc;
      resize: none;
      outline: hidden;
      background-color: transparent;
      font-size: 14px;
      font-family: "Monaco", courier, monospace;
      padding: 20px;
    }*/

code {
    color: #f66;
}

.container {
    max-width: 960px;
}

.lh-condensed {
    line-height: 1.25;
}

.bd-links {
    overflow: auto;
    font-weight: 600;
}

.bd-layout {
    display: grid;
    gap: 1.5rem;
    grid-template-areas: "sidebar main";
    grid-template-columns: 1fr 3fr;
}

.bd-sidebar {
    margin: 0 -.75rem 1rem;
}

.highlight pre {
    padding: 0;
    margin-top: .65rem;
    margin-bottom: .65rem;
    white-space: pre;
    background-color: transparent;
    border: 0;
}

.highlight {
    padding: 1rem;
    margin-bottom: 1rem;
    background-color: #f8f9fa;
}

.bd-placeholder-img {
    font-size: 1.125rem;
    text-anchor: middle;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

@media (min-width: 768px) {
    .bd-placeholder-img-lg {
        font-size: 3.5rem;
    }
}

.zhuangbi {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    width: 180px;
    height: 180px;
    margin: auto;
    border-radius: 50%;
    background: rgb(58, 27, 170);
    overflow: hidden;
}

.zhuangbi::before {
    content: "";
    width: 500px;
    height: 500px;
    border-radius: 40%;
    background-color: rgba(255, 255, 255, 0.6);
    display: block;
    transform: translate(-28%, -80%);
    animation: move 5s infinite linear;
}

@keyframes move {
    0% {
        transform: translate(-28%, -78%) rotateZ(0);
    }

    100% {
        transform: translate(-28%, -78%) rotateZ(360deg);
    }
}

.turn2 {
    position: absolute;
    width: 100%;
    height: 420px;
    perspective: 700px;
    opacity: 0;
    transition: 2s;
}

.turn2 p {
    padding: 3px;
    color: thistle;
    font-size: 20px;
    font-weight: 800;
    position: relative;
    top: 130px;
    text-align: center;
}
</style>
